package com.test.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.test.filter.JwtSecurityFilter;
import com.test.mapper.UserMapper;
import com.test.utils.JwtUtils;
import com.test.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class SecurityConfig {

    @Autowired
    UserMapper userMapper;
    @Autowired
    JwtSecurityFilter JwtSecurityFilter;
    @Autowired
    JwtUtils jwtUtils;
    @Bean
    SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        return http
                .authorizeHttpRequests(conf -> conf
                        .requestMatchers("/api/**").permitAll()
                        .anyRequest().authenticated())
                .formLogin(conf -> conf
                        .loginProcessingUrl("/api/login")
                        .successHandler((request, response, authentication) -> {
                            response.setContentType("application/json;charset=utf-8");
                            User user = (User) authentication.getPrincipal();
                            String username = user.getUsername();
                            QueryWrapper<com.test.domain.dto.User> wrapper = new QueryWrapper<>();
                            wrapper.eq("username", username);
                            com.test.domain.dto.User user1 = userMapper.selectOne(wrapper);
                            Map<String , String> mp = new HashMap<>();
                            mp.put("username",username);
                            mp.put("id", user1.getId()+"");
                            mp.put("rid", user1.getRid());
                            String token = jwtUtils.CreateToken(mp);
                            response.getWriter().write(Result.success(token).toString());
                        })
                        .failureHandler((request, response, exception) -> {
                            response.setContentType("application/json;charset=utf-8");
                            response.getWriter().write(Result.error("登录失败").toString());
                        }))
                .logout(conf -> conf
                        .logoutUrl("/api/logout")
                        .logoutSuccessHandler((request, response, authentication) -> {
                            response.setContentType("application/json;charset=utf-8");
                            if (jwtUtils.DeleteJwt(request.getHeader("Authorization")))
                                response.getWriter().write(Result.success("退出成功").toString());
                            else
                                response.getWriter().write(Result.error("退出失败").toString());
                        }))
                .exceptionHandling(conf -> conf
                        .authenticationEntryPoint((request, response, exception) -> {
                            response.setContentType("application/json;charset=utf-8");
                            response.getWriter().write(Result.error("未登录").toString());
                        })
                        .accessDeniedHandler((request, response, exception) -> {
                            response.setContentType("application/json;charset=utf-8");
                            response.getWriter().write(Result.error("权限不足").toString());
                        }))
                .csrf(conf -> conf.disable())
                .sessionManagement(conf -> conf
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .addFilterBefore(JwtSecurityFilter , UsernamePasswordAuthenticationFilter.class)
                .build();
    }
}
